<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="科研实验方案" v-bind="validateInfos.entrustId">
            <JDictSelectTag v-model:value="formData.entrustId" dictCode="lab_wscientific,plan_title,id" size="large"
              class="input" :show-choose-option="true" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="实验项目名称" v-bind="validateInfos.itemName">
            <a-input v-model:value="formData.itemName" :disabled="disabled" size="large" class="input"
              style="width: 360px;" />
            <a-button style="color:rgb(80, 173, 255);left: 10px;" size="large" class="input"
              @click="openForm()">引入实验模板</a-button>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="实验人员" v-bind="validateInfos.userName">
            <a-input v-model:value="formData.userName" size="large" class="input" :disabled="disabled"
              @click="handleAuditModal2" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="复核人员" v-bind="validateInfos.auditName">
            <a-input v-model:value="formData.auditName" size="large" class="input" @click="handleAuditModal" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="开始日期" v-bind="validateInfos.pubDate">
            <a-date-picker placeholder="" v-model:value="formData.pubDate" value-format="YYYY-MM-DD" size="large"
              class="input" style="width: 100%" :default-value="getPubDate()" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="截至日期" v-bind="validateInfos.finDate">
            <a-date-picker placeholder="" v-model:value="formData.finDate" value-format="YYYY-MM-DD" size="large"
              class="input" style="width: 100%" :default-value="getFinDate()" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-input v-model:value="formData.remark" :disabled="disabled" />
          </a-form-item>
        </a-col> -->
      </a-row>
    </a-form>
  </a-spin>
  <LabTemPOD @register="registerTenms" @getRatifyResultS2="onAuditOks1"></LabTemPOD>
  <TableUserModal @register="registerUserModal" @getAuditResult="onAuditOk" />
  <TableUserModal @register="registerUserModal2" @getAuditResult="onAuditOk2" />

  <TableModal @register="registerItemsModal"></TableModal>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
import { useModal } from '/@/components/Modal';
import { useMessage } from '/@/hooks/web/useMessage';
import { getValueType } from '/@/utils';
import { itemSaveOrUpdate,byTidList } from '../LabWscientific.api';
import { Form } from 'ant-design-vue';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import LabTemPOD from '../../wscientific_item/components/LabTemPOD.vue';
import TableUserModal from '../../wscientific_item/components/LabUserTableList.vue';
import moment from 'moment';
import TableModal from '../../items_check/LabCheckItemsFrom.vue';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => { } },
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const getPubDate = () => {
  return moment().format('YYYY-MM-DD');
}
const getFinDate = () => {
  return moment().add('15', 'days').format('YYYY-MM-DD');
}
const formData = reactive<Record<string, any>>({
  id: '',
  entrustId: '',
  itemId: '',
  itemName: '',
  itemStatus: '待实验',
  userId: '',
  userName: '',
  auditId: '',
  auditName: '',
  pubDate: getPubDate(),
  finDate: getFinDate(),
  entrustType: '科研项目',
  remark: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {
  itemName: [{ required: true, message: '请输入项目名称!' }],
  userName: [{ required: true, message: '请选择实验人员!' }],
  auditName: [{ required: true, message: '请选择复核人员!' }],
  pubDate: [{ required: true, message: '请选择开始日期!' }],
  finDate: [{ required: true, message: '请选择截至日期!' }],
};



const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
const [registerUserModal, { openModal: openUModal }] = useModal();
const [registerUserModal2, { openModal: openUModal2 }] = useModal();
const [registerTenms, { openModal: openUModals1 }] = useModal();
//注册model
const [registerItemsModal, { openModal: openModals3 }] = useModal();
// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});


function handleAuditModal() {
  openUModal(true, {
    oper: 'audit',
  });
}

// 选择复核人员
function onAuditOk(uId, uName) {
  formData.auditId = uId;
  formData.auditName = uName;
}

//打开检测人员列表
function handleAuditModal2() {
  openUModal2(true, {
    oper: 'audit',
  });
}

/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    //赋值
    formData.entrustId = record.id;
    formData.userName = record.planUsers;
    byTidList({ "tId": record.planUsersId }).then(src=> {
       formData.userId = src.result;
    });
    // Object.assign(formData, record);
  });
}

//打开选择模板
function openForm() {
  openUModals1(true, {
    oper: 'audit',
  });
}
// 选择检测人员
function onAuditOk2(uId, uName) {
  formData.userId = uId;
  formData.userName = uName;
}
// 选择模板
function onAuditOks1(uId, uName) {
  formData.itemId = uId;
  formData.itemName = uName;
}
/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  await itemSaveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        // console.log(res.result);
        // createMessage.success(res.message);
        emit('ok');
        const record = {
          id: res.result.id,
          entrustId: res.result.entrustId,
          itemId: res.result.itemId,
          itemName: res.result.itemName,
          samName: res.result.samName,
          auditId: res.result.auditId,
          auditName: res.result.auditName,
        }
        openModals3(true, {
          record,
          disabled: false,
        });
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


defineExpose({
  add,
  edit,
  openForm,
  onAuditOk,
  onAuditOk2,
  onAuditOks1,
  submitForm,
  handleAuditModal,
  handleAuditModal2
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  min-height: 500px !important;
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}
</style>
